package com.yc.spring.bank.dao;

import com.yc.spring.bank.bean.Account;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;


@Component
public class AccountDaoImpl implements  AccountDao{

    @Resource
    JdbcTemplate jdbcTemplate;

    @Override
    public void insert(Account t) {
        String sql = "insert into bank_account values(?,null,?)";
        jdbcTemplate.update(sql,t.getId(),t.getMoney());

    }

    @Override
    public void update(Account t) {
        String sql = "update bank_account  set balance=? where id=?";
        jdbcTemplate.update(sql,t.getMoney(),t.getId());

    }

    @Override
    public Account selectById(Integer id) {
        String sql = "select * from bank_account where id=?";
        Account account = jdbcTemplate.queryForObject(sql, new RowMapper<Account>() {

            @Override
            public Account mapRow(ResultSet resultSet, int i) throws SQLException {
                Account ret = new Account();
                ret.setId(resultSet.getInt("id"));
                ret.setMoney(resultSet.getDouble("balance"));
                return ret;
            }
        });
        return account;
    }
}
